import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { AuthContext } from "@/App";
import { useContext } from "react";
import { toast } from "sonner";
import Navbar from "@/components/Navbar";
import Sidebar from "@/components/Sidebar";
import MainContent from "@/components/MainContent";
import axios from '../utils/axios';

// const notifications = [
//   { id: 1, title: "新的患者申请", read: false },
//   { id: 2, title: "保险审批通过", read: true },
//   { id: 3, title: "系统维护通知", read: false }
// ];

// interface MenuItem {
//   id: number;
//   name: string;
//   icon: string;
// }

const menuList = [
  { id: 1, name: "医疗记录", icon: "fa-regular fa-file-lines" },
  { id: 2, name: "医院管理", icon: "fa-solid fa-hospital" },
  { id: 3, name: "实验室管理", icon: "fa-solid fa-flask" },
  { id: 4, name: "保险管理", icon: "fa-solid fa-shield" },
  { id: 5, name: "系统管理", icon: "fa-solid fa-gear" },
];

export default function Dashboard() {
  const [activeMenu, setActiveMenu] = useState(0);
  // const [showNotifications, setShowNotifications] = useState(false);
  // const [showUserMenu, setShowUserMenu] = useState(false);
  const [avaliableMenu, setAvaliableMenu] = useState(menuList);

  const { logout } = useContext(AuthContext);
  const navigate = useNavigate();
  // const [userData, setUserData] = useState({
  //   name: "",
  //   avatar: "",
  //   role: ""
  // });

  // 添加获取用户数据的函数
  // const fetchUserData = async () => {
  //   try {
  //     const response = await axios.get('/api/v1/user', {
  //       withCredentials: true
  //     });
  //     setUserData(response.data);
  //   } catch (error) {
  //     console.error('获取用户数据失败:', error);
  //   }
  // };

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const response = await axios.post('/api/check-auth', {}, {
          withCredentials: true
        });
        if (!response.data.isAuthenticated) {
          throw new Error('未登录');
        }
      } catch (error) {
        toast.error('请重新登录');
        logout();
        navigate('/login');
      }
    };

    const fetchMenuItems = async () => {
      try {
        const response = await axios.get('api/v1/menuitems', {
          headers: {
            'Accept': 'application/json' // 明确要求JSON响应
          }
        });
        const data = response.data;
        console.log("拉取所有可用菜单列表：", response);

        const availableMenus = menuList.filter(menuItem => 
          data.menuItems.some((item: number) => item === menuItem.id)
        );
        setAvaliableMenu(availableMenus);

        // 更新全局menuItems变量
        console.log('获取的菜单项:', availableMenus);
      } catch (error) {
        console.error('获取菜单项失败:', error);
      }
    };

    checkAuth();
    fetchMenuItems();
    // fetchUserData(); // 新增调用
  }, [navigate, logout]);

  // const unreadCount = notifications.filter(n => !n.read).length;

  const handleMenuClick = (id: number) => {
    console.log("activated menu: ", id);
    setActiveMenu(id);
  };

  // const handleLogout = async () => {
  //   try {
  //     // 先调用后端退出接口
  //     await axios.post('/api/logout', {}, {
  //       withCredentials: true
  //     });
      
  //     // 然后执行前端退出逻辑
  //     logout();
  //     toast.success("已退出登录");
  //     navigate("/login");
  //   } catch (error) {
  //     console.error('退出登录失败:', error);
  //     toast.error('退出登录失败');
  //   }
  // };

  return (
    <div className="flex h-screen flex-col">
      <Navbar />
      <div className="flex flex-1 overflow-hidden">
        <Sidebar
          menuItems={avaliableMenu}
          activeMenu={activeMenu}
          handleMenuClick={handleMenuClick}
        />
        <MainContent activeMenu={activeMenu} />
      </div>
    </div>
  );
}
